import StateTab from '@/components/StateTab';
import { message, Spin, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { connect, Link } from 'umi';
import ExportFormData from '@/components/ExportFormData';
import { CurrentUserProps } from '@/types';
import styles from './index.less';
import { getProfitData, getProfitTotal } from './service';

const { log } = console;
let listStatus: any = null;
const Profit: React.FC<{ currentUser: CurrentUserProps }> = ({ currentUser }) => {
  const [pageLoading, setPageLoading] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<[]>([]);
  const [count, setCount] = useState<number>(0);
  const [moneyData, setMoneyData] = useState<{}>({ totalIncomes: '', waitSettle: '' });

  const [pageCurrent, setPageCurrent] = useState<number>(1);

  const profitTotalView = async () => {
    const { code, data, info } = await getProfitTotal();

    if (code != 0) {
      message.error(info);
      return;
    }

    setMoneyData({ ...data });
  };

  const listView = (status = null) => {
    return async (pageIndex = 1, pageSize = 10) => {
      listStatus = status;
      setLoading(true);

      setPageCurrent(pageIndex);
      const { code, info, count: backCount, data } = await getProfitData({
        status,
        pageIndex,
        pageSize,
      });

      setLoading(false);
      if (code != 0) {
        message.error(info);
        return;
      }

      const list = data.map((item, index: number) => {
        const {
          settle,
          curMonthIncomes,
          preTaxIncomes,
          withholdingTax,
          afterTaxIncomes,
          status: state,
        } = item;
        /* eslint-disable */
        return {
          key: index,
          settle,
          curMonthIncomes,
          preTaxIncomes: preTaxIncomes || '-',
          withholdingTax,
          afterTaxIncomes,
          status: state,
        };
      });

      setLoading(false);
      setCount(backCount);
      setDataSource(list);
    };
  };

  let listViewWithState = listView(null);

  useEffect(() => {
    Promise.all([profitTotalView(), listViewWithState()]).then(() => {
      log('all end');
      setPageLoading(false);
    });
  }, []);

  const handleChange = async (item) => {
    listViewWithState = listView(item.state);
    listViewWithState();
  };

  const tabColumns = [
    {
      key: 'title',
      text: '状态',
    },
    {
      key: 'tab',
      text: '全部',
      state: null,
    },
    {
      key: 'tab',
      text: '已支付',
      state: 2,
    },
    {
      key: 'tab',
      text: '付款中',
      state: 1,
    },
    {
      key: 'tab',
      text: '付款失败',
      state: 3,
    },
  ];

  const columns = [
    {
      title: '结算周期',
      dataIndex: 'settle',
      key: 'settle',
    },
    {
      title: '本月收益',
      dataIndex: 'curMonthIncomes',
      key: 'curMonthIncomes',
    },
    {
      title: '税前金额',
      dataIndex: 'preTaxIncomes',
      key: 'preTaxIncomes',
      render: (value: any) => value || '-',
    },
    {
      title: '代扣税',
      dataIndex: 'withholdingTax',
      key: 'withholdingTax',
      render: (value: any, item: { status: string }) => {
        if (currentUser.isLeader && item.status === '不结算') {
          return value || '-';
        }
        return value;
      },
    },
    {
      title: '税后金额',
      dataIndex: 'afterTaxIncomes',
      key: 'afterTaxIncomes',
      render: (value: any) => value || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
  ];

  return (
    <div className={styles.main}>
      <Spin spinning={pageLoading}>
        <div className={styles.header}>
          <div className={styles['money-view']}>
            <div className={styles['money-box']}>
              <div className={styles['money-total']}>
                累计收益：<span>{moneyData.totalIncomes} 元</span>
              </div>
              <div className={styles['money-total']}>
                待结算：<span>{moneyData.waitSettle} 元</span>
              </div>
            </div>
            <Link className={styles['money-btn']} to="/person/profit/setting">
              结算设置
            </Link>
          </div>
          {currentUser.isLeader && (
            <p className={styles['leader-money']}>
              内容收益：<span>{moneyData.contentIncomes ? moneyData.contentIncomes : 0} 元</span>
            </p>
          )}
          {currentUser.isLeader && (
            <p className={styles['leader-money']}>
              组员抽成：
              <span>{moneyData.commissionIncomes ? moneyData.commissionIncomes : 0} 元</span>
            </p>
          )}
        </div>
        <div className={styles.content}>
          <div className={styles['content-title']}>结算记录</div>
          <StateTab tabs={tabColumns} selectTab={handleChange} />

          <ExportFormData
            count={count}
            action="/service/partTimerWb/user/searchIncomes"
            data={{ status: listStatus }}
            columns={['结算周期', '本月收益', '税前金额', '代扣税', '税后金额', '状态']}
            afterRequest={(response) => {
              console.log('response', response);
              return (
                response.data &&
                response.data.map((item) => {
                  const {
                    settle,
                    curMonthIncomes,
                    preTaxIncomes,
                    withholdingTax,
                    afterTaxIncomes,
                    status,
                  } = item;
                  return {
                    settle,
                    curMonthIncomes,
                    preTaxIncomes: preTaxIncomes || '-',
                    withholdingTax: withholdingTax || '-',
                    afterTaxIncomes: afterTaxIncomes || '-',
                    status,
                  };
                })
              );
            }}
          />

          <Table
            dataSource={dataSource}
            loading={loading}
            columns={columns}
            pagination={{
              pageSize: 10,
              total: count,
              current: pageCurrent,
              onChange: (index, size) => {
                listViewWithState(index, size);
              },
            }}
            bordered
          />
        </div>
      </Spin>
    </div>
  );
};

export default connect(({ user: currentUser }: { user: CurrentUserProps }) => ({ ...currentUser }))(
  Profit,
);
